﻿using System;
using System.Configuration;
using System.IO;
using Icms.Core.Service;

namespace Icms.Service
{
    public class FileManagerService : IFileManagerService
    {
        private readonly string path = ConfigurationManager.AppSettings["storagePath"];
        public Stream GetStream(byte[] bytes)
        {

            var ms = new MemoryStream();

            var byteInfo = bytes;
            ms.Write(byteInfo, 0, byteInfo.Length);
            ms.Position = 0;

            return ms;
        }
        public string Save(Stream inputStream, string name)
        {
            var g = Guid.NewGuid();
            using(var writeStream = new FileStream(path+"/"+g+name, FileMode.Create, FileAccess.Write))
            {
                const int Length = 256;
                var buffer = new Byte[Length];
                var bytesRead = inputStream.Read(buffer, 0, Length);
                
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = inputStream.Read(buffer, 0, Length);
                }

                inputStream.Close();
            }
            return g + name;
        }

        public byte[] GetBytes(string fileName)
        {
            var fs = new FileStream(path+"/"+fileName, FileMode.Open, FileAccess.Read);
            var br = new BinaryReader(fs);
            var numBytes = new FileInfo(path + "/" + fileName).Length;
            var buff = br.ReadBytes((int) numBytes);
            return buff;
        }
    }
}